import VueRouter from "vue-router";
//引入Vue
import Vue from "vue";
import store from "@/store";
Vue.use(VueRouter);
const Detail = () => import("@/pages/Detail");
const Search = () => import("@/pages/Search");
const AddCartSuccess = () => import("@/pages/AddCartSuccess");
const ShopCart = () => import("@/pages/ShopCart");
const Register = () => import("@/pages/Register");
const Login = () => import("@/pages/Login");
const Trade = () => import("@/pages/Trade");
const Pay = () => import("@/pages/Pay");
const PaySuccess = () => import("@/pages/PaySuccess");
const Order = () => import("@/pages/Center");
const MyOrder = () => import("@/pages/Center/myOrder");
const GroupBuy = () => import("@/pages/Center/groupOrder");

//需要重写VueRouter.prototype原型对象身上的push|replace方法
//先把VueRouter.prototype身上的push|replace方法进行保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
//重写VueRouter.prototype身上的push方法了
VueRouter.prototype.push = function (location, resolve, reject) {
  //第一个形参：路由跳转的配置对象（query|params）
  //第二个参数：undefined|箭头函数（成功的回调）
  //第三个参数:undefined|箭头函数（失败的回调）
  if (resolve && reject) {
    //push方法传递第二个参数|第三个参数（箭头函数）
    //originPush：利用call修改上下文，变为(路由组件.$router)这个对象，第二参数：配置对象、第三、第四个参数：成功和失败回调函数
    originPush.call(this, location, resolve, reject);
  } else {
    //push方法没有产地第二个参数|第三个参数
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};
//重写VueRouter.prototype身上的replace方法了
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject);
  } else {
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    );
  }
};
let router = new VueRouter({
  routes: [
    {
      path: "/",
      redirect: "/home",
    },
    { path: "/home", component: () => import("@/pages/Home") },

    {
      name: "search", // 是当前路由的标识名称
      path: "/search/:keyword?",
      component: Search,
      // 将params参数和query参数映射成属性传入路由组件
      props: (route) => ({
        keyword3: route.params.keyword,
        keyword4: route.query.keyword2,
      }),
    },
    {
      name: "detail", // 是当前路由的标识名称
      path: "/detail/:skuId",
      component: Detail,
    },

    {
      name: "addcartsuccess",
      path: "/addcartsuccess",
      component: AddCartSuccess,
    },
    {
      path: "/shopcart",
      component: ShopCart,
    },
    {
      path: "/register",
      component: Register,
    },
    {
      path: "/login",
      component: Login,
    },
    {
      path: "/trade",
      component: Trade,
      //路由独享
      beforeEnter: (to, from, next) => {
        if (from.path == "/shopcart") {
          next();
        } else {
          next(false);
        }
      },
    },
    {
      path: "/pay",
      component: Pay,

      /* 只能从交易界面, 才能跳转到支付界面 */
      beforeEnter(to, from, next) {
        if (from.path === "/trade") {
          next();
        } else {
          next("/trade");
        }
      },
    },
    {
      path: "/paysuccess",
      component: PaySuccess,
      beforeEnter(to, from, next) {
        if (from.path === "/pay") {
          next();
        } else {
          next("/pay");
        }
      },
    },
    {
      path: "/center",
      component: Order,

      children: [
        {
          path: "",
          redirect: "myorder",
        },
        {
          path: "myorder",
          component: MyOrder,
        },
        {
          path: "grouporder",
          component: GroupBuy,
        },
      ],
    },
  ],
  //   重写push与replace方法
  //   工作的时候想处理掉，不想处理对于你的程序没有任何影响
  // eslint-disable-next-line no-unused-vars
  scrollBehavior(to, from, savedPosition) {
    //返回的这个y=0，代表的滚动条在最上方
    return { y: 0 };
  },
});
//全局守卫：前置守卫（在路由跳转之间进行判断）
router.beforeEach(async (to, from, next) => {
  //to:获取到要跳转到的路由信息
  //from：获取到从哪个路由跳转过来来的信息
  //next: next() 放行  next(path) 放行
  //方便测试 统一放行
  //  next();
  //获取仓库中的token-----可以确定用户是登录了
  let token = store.state.user.token;
  let name = store.state.user.userInfo.name;
  //用户登录了
  if (token) {
    //已经登录而且还想去登录------不行
    if (to.path == "/login" || to.path == "/register") {
      next("/");
    } else {
      //已经登陆了,访问的是非登录与注册
      //登录了且拥有用户信息放行
      if (name) {
        next();
      } else {
        //登陆了且没有用户信息,刷新没有，先获取用户信息在放行
        //在路由跳转之前获取用户信息且放行
        try {
          await store.dispatch("user/getUserInfo");
          next();
        } catch (error) {
          //token失效从新登录
          await store.dispatch("user/userLogout");
          next("/login");
        }
      }
    }
  } else {
    if (
      to.path.includes("/trade") ||
      to.path.includes("/pay") ||
      to.path.includes("/center")||
      to.path.includes("/shopcart")
    ) {
      next("/login?redirect=" + to.path);
    }
    //不是以上可以放行
    next();
  }
});
export default router;
